package com.study.wumeng.androidandh5;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;


/**
 * @author WuMeng
 */
public class JsCallJavaCallPhoneActivity extends AppCompatActivity {

    private WebView webView;
    private Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_js_call_java_call_phone);

        isGrantExternalRW(this);

        webView = findViewById(R.id.webView2);

        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        webView.setWebViewClient(new WebViewClient());

        webView.addJavascriptInterface(new AndroidAndJsInterface(), "Android");

        webView.loadUrl("file:///android_asset/JsCallJavaCallPhone.html");
    }

    class AndroidAndJsInterface {

        @JavascriptInterface
        public void showcontacts() {
            final String json = "[{\"name\":\"阿福\", \"phone\":\"18600012345\"}]";
            handler.post(new Runnable() {
                @Override
                public void run() {
                    webView.loadUrl("javascript:show(" + json + ")");
                }
            });

        }

        @JavascriptInterface
        public void call(String phone) {
            Toast.makeText(JsCallJavaCallPhoneActivity.this, "哈哈", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone));
            if (ActivityCompat.checkSelfPermission(JsCallJavaCallPhoneActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            startActivity(intent);
        }
    }

    /**
     * 获取储存权限
     *
     * @param activity
     * @return
     */

    public static boolean isGrantExternalRW(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && activity.checkSelfPermission(
                Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {

            activity.requestPermissions(new String[]{
                    Manifest.permission.CALL_PHONE
            }, 1);

            return false;
        }

        return true;
    }

}
